import EmptyRecord from '../../components/EmptyRecord/EmptyRecord.vue';
import PromptPopup from '../../components/PromptPopup/PromptPopup.vue';
import api from '@/http/api.js';
import util from '@/http/util.js';
import date from '@/computingTool/date.js';
export default {
	components: {
		PromptPopup,
		EmptyRecord
	},
  data() {
    return {
      tabs: ['待支付', '待确认', '已收款', '暂停中', '已取消'],
      activeTab: 0,
      scrollLeft: 0,
	  
	  tesList:[],//测试数组
	  tradeList:[],
	  page: 1, // 当前页码
	  pageSize: 10, // 每页数据量
	  isLoading: true, // 防止重复加载
	  noMoreData: false, // 是否已无更多数据
	  
	  option:'',//弹窗模板
	  popuptxt:'',//弹窗提示语
	  popupType:'',//弹窗的类型、用途标识
	  confirmTxt:'',//确认按钮默认文字
	  
	  /* 状态管理start*/
	  chOrderId:'',//选中的订单id
	  chOrderStarts:'',//选中订单的状态
	  /* 状态管理end*/
	  
	  statusBarHeight: 0,
	  
	  userInfo: {}, //用户信息
	  userAllInfo:{},//用户详细信息，包含资金
    }
  },
  mounted() {
    // 获取用户信息
    this.userInfo = util.getUserInfo();
  },
  onLoad() {
	  this.getUerInfo();
  	//this.loadData(); // 首次加载数据
	// 动态获取状态栏高度（App 端）
	    // #ifdef APP-PLUS
	    this.statusBarHeight = plus.navigator.getStatusbarHeight();
	    // #endif
  },
  onShow(){
	  this.loadData(); // 首次加载数据
	  this.getUerInfo();//用户资金信息
	  this.userInfo = util.getUserInfo();
  },
  computed: {
  	totalNavHeight() {
  	  const app = getApp();
  	  // 确保 globalData 存在，提供默认值
  	  return (app.globalData?.statusBarHeight || 0) + (app.globalData?.navBarHeight || 44);
  	}
  },
  methods: {
    selectTab(index) {
      this.activeTab = index;
	  this.page = 1;
	  this.loadData();//选项卡切换，刷新数据
    },
	//获取用户数据
	getUerInfo(){
		api.getUerInfo().then(res=>{
			if(res.code==1){
				this.userAllInfo = res.data;
				const myrebte = (res.data.col_today_my_rebate + res.data.pay_today_my_rebate).toFixed(2);
				const totalrebte = (res.data.col_today_total_rebate + res.data.pay_today_total_rebate).toFixed(2);
				const userebte = (res.data.money - res.data.freeze_money).toFixed(2);
				this.userAllInfo.all_my_rebate = parseFloat(myrebte);
				this.userAllInfo.all_total_rebate = parseFloat(totalrebte);
				this.userAllInfo.can_use_balance = parseFloat(userebte);
			}
		})
	},
    // 初始化加载数据
    loadData() {
		this.page = 1;
		api.getCollection({
		  status:this.activeTab,
		  page: this.page,
		  limit: this.pageSize
		}).then(res=>{
			if(res.code == 1){
				this.tradeList = res.data.list;
				this.noMoreData = false;
			}else{
				uni.showToast({ title: res.msg, icon: 'none' });
			}
		}).catch(err=>{
			console.error('加载数据失败:', err);
		}).finally(fee=>{
			this.isLoading = false;
		})
    },
	//多次加载，拼接数据
	moreData() {
		this.page++;
		api.getCollection({
		  status:this.activeTab,
		  page: this.page,
		  limit: this.pageSize
		}).then(res=>{
			if(res.code==1){
				if (res.data.list.length === 0) {
				  this.noMoreData = true; // 标记无更多数据
				  uni.showToast({ title: '没有更多数据了', icon: 'none' });
				  this.page--;
				} else {
					this.tradeList = [...this.tradeList, ...res.data.list]; // 合并新数据
				}
			}else{
				uni.showToast({ title: res.msg, icon: 'none' });
			}
			
		}).catch(err=>{
			console.error('加载数据失败:', err);
		}).finally(fee=>{
			this.isLoading = false;
		})
	},
    switchTab(index) {
    	this.activeTab = index;
    	if(index == 1){
    		this.tradeList = [];
    	}else{
    		this.tradeList = [1, 2, 3, 4, 5, 6, 7, 8,1, 2, 3, 4, 5, 6, 7, 8];
    	}
    	// 添加加载对应数据的逻辑
    },
	//跳转客服
	goweb(){
		api.deploy().then(res=>{
			if(res.code==1){
				//#ifdef APP-PLUS
				plus.runtime.openURL(res.data.service, (err) => {
				  if (err) {
				    uni.showToast({ title: '打开浏览器失败', icon: 'none' });
				    // 降级方案：复制链接到剪贴板
				    uni.setClipboardData({
				      data: res.data.service,
				      success: () => {
				        uni.showToast({ title: '链接已复制，请手动打开浏览器粘贴', icon: 'none' });
				      }
				    });
				  }
				});
				// #endif
				
				// #ifdef H5
				window.open(res.data.service, '_blank');
				// #endif
			}else{
				uni.showToast({ title: res.msg, icon: 'none' });
			}
		})
	},
	//确认订单前提示
	waitConfirm(item,type){
		if(type == 1){
			this.popuptxt = '是否确认收款';
		}else if(type == 2){
			this.popuptxt = '是否确认未收到款';
		}
		this.popupType = 'confirmPayment';
		this.option = '1';
		this.chOrderId = item.id;
		this.chOrderStarts = type;
		this.$refs.pointOut.open();
	},
	/* 过滤器start */
	//收款渠道
	paytype(value){
		if(value==1){
			return '银行卡'
		}else if(value==2){
			return '微信'
		}else if(value==3){
			return '支付宝'
		}else if(value==4){
			return '云闪付'
		}else if(value==5){
			return '数字人民币'
		}else if(value==6){
			return '钉钉'
		}
	},
	//收款渠道图片
	payimg(value){
		if(value==1){
			return '/static/payImg/yinghangkazhuangzhang.png'
		}else if(value==2){
			return '/static/payImg/weixin.png'
		}else if(value==3){
			return '/static/payImg/zhifubao.png'
		}else if(value==4){
			return '/static/payImg/yunshanfu.png'
		}else if(value==5){
			return '/static/payImg/shuzirenmingbi.png'
		}else if(value==6){
			return '/static/payImg/dingding.png'
		}
	},
	//订单状态
	orderStart(value){
		if(value==0){
			return '待支付'
		}else if(value==1){
			return '待确认'
		}else if(value==2){
			return '已收款'
		}else if(value==3){
			return '暂停中'
		}else if(value==4){
			return '已取消'
		}
	},
	//时间戳
	timeString(value){
		// 1. 转换时间戳
		const timestamp = value;
		const millis = timestamp * 1000;
		
		// 2. 格式化为字符串"2025-07-18 17:59:55" (北京时间)
		const dateStr = new Date(millis).Format("yyyy-MM-dd hh:mm:ss");
		return dateStr
		
		// 3. 使用自定义格式 "2025年07月18日 17时59分"
		// const customFormat = new Date(millis).Format("yyyy年MM月dd日 hh时mm分");
	},
	/* 过滤器end */
	//复制订单号
	copyOrderNumber(orderNumber){
		uni.setClipboardData({
			data: orderNumber,
			success: () => {
				uni.showToast({
					title: '订单号已复制',
					icon: 'success'
				});
			}
		});
	},
	//充值提示
	topUp(){
		this.option = '1';
		this.popuptxt = "充值请联系客服"
		this.$refs.pointOut.open();
	},
	//历史订单
	order(){
		uni.navigateTo({
			url:'/pages/My/HistoricalOrder/index'
		})
	},
	//收款管理
	collectMoney(data){
		let that = this;
		if(data.popupType == 'confirmPayment'){
			api.confirmPayment({
				id:this.chOrderId,
				status:this.chOrderStarts
			}).then(res=>{
				if(res.code==1){
					if(this.chOrderStarts==1){
						uni.showToast({ title: '收款已经确认', icon: 'none' });
					}else{
						uni.showToast({ title: res.msg, icon: 'none' });
					}
					// uni.showLoading();
					// setTimeout(function () {
					// 	uni.hideLoading();
					// }, 1000);
					that.loadData();
				}else{
					uni.showToast({ title: res.msg, icon: 'none' });
				}
			}).catch(err=>{
				console.error('加载数据失败:', err);
			}).finally(fee=>{
				this.$refs.pointOut.closeModal();
				this.loadData();
			})
			return
		}
		if(this.option==1){
			this.option = '';
			this.popuptxt = '';
			this.$refs.pointOut.closeModal();
			return
		}
		this.$refs.pointOut.closeModal();
		uni.navigateTo({
			url:'/pages/Home/CollectionManagement/index'
		})
	},
	//新手教程
	Tutorial(){
		uni.navigateTo({
			url:'/pages/Home/Tutorial/index'
		})
	},
	//转账
	TransferAccounts(){
		uni.navigateTo({
			url:'/pages/Home/TransferAccounts/index'
		})
	},
	//系统公告
	announcement(){
		uni.navigateTo({
			url:'/pages/Home/announcement/index'
		})
	},
	//滚动底部，请求新数据
	GetNewData(){
		console.log("请求数据")
	  if (this.isLoading || this.noMoreData) return; // 避免重复加载
	  this.isLoading = true;
	  this.moreData();
	},
	//提示弹窗
	tradePassword() {
	  this.option = '0';
	  this.$refs.pointOut.open();
	},
  },

}